/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-05-25 19:50:13
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:16:35
 */

'use strict';
define([
    '../../../framework/base/baseView',
    '../../../framework/bean/ecCreativeTemplate',
    './chooseDialog',
    './highEdit',
    'text!../tpl/step2.html',
    './modernizr.custom',
], function(
    BaseView,
    ecCreativeTemplateModel,
    ChooseDialogView,
    HighEditView,
    tpl
) {
    function me() {
        window.$ = $;
        BaseView.apply(this, arguments);
        var self = this;

        //当前页面移动完毕
        var endCurrPage = false;
        //后续页面移动完毕
        var endNextPage = false;

        var animEndEventNames = {
            'WebkitAnimation': 'webkitAnimationEnd',
            'OAnimation': 'oAnimationEnd',
            'msAnimation': 'MSAnimationEnd',
            'animation': 'animationend'
        };
        // animation end event name
        var animEndEventName = animEndEventNames[Modernizr.prefixed('animation')]
        /**
         * [init description]
         * @param  {[type]} $root    [description]
         * @param  {[type]} jumpStep [description]
         * @param  {[type]} restore  [是否从缓存恢复]
         * @return {[type]}          [description]
         */
        this.init = function($root, jumpStep, restore) {
            jumpStep(2);
            self.$root = $root;
            self.restore = restore;
            self.step1Key = 'createMaterialStep1'; //step1缓存
            self.step2Key = 'createMaterialStep2'; //step2缓存

            self.render();
        }

        this.render = function() {
            self.$root.html(I18N.parse(tpl,'createMaterial'));
            self.$major = self.$root.find('#majorElement');
            self.$minor = self.$root.find('#minorElement');
            self.$majorFill = self.$root.find('#majorFill');
            self.$minorFill = self.$root.find('#minorFill');

            //保存各个View的默认class
            $(".pt-page").each( function() {
                var $page = $( this );
                $page.data( 'originalClassList', $page.attr( 'class' ) );
            } );
            //设置默认页面
            $(".pt-page").eq(0).addClass( 'pt-page-current' );

            //初始化缓存的值
            self.loadCache();
            self.event();

        }

        this.event = function() {

            self.$root.find('.step2-input .btn-default').off('click').on('click', $.proxy(self.openChooseDialog, self));
            //主要元素、次要元素切换
            self.$root.find('.step2-swich-btn-div').off('click').on('click', $.proxy(self.swapElement, self));
            //生成预览 button事件
            self.$root.find('.btn-generte').off('click').on('click', $.proxy(self.generate, self));

            //进入高级编辑
            self.$root.find('.high-edit').off('click').on('click', $.proxy(self.openHighEditView, self));
            self.$root.find('.high-close1').off('click').on('click', $.proxy(self.closeHighEditView, self));

            //第二步提交
            self.$root.find('.btn-next').off('click').on('click', $.proxy(self.submitStep2, self));

        }

        //所有动画都结束后
        this.onEndAnimation = function ($outpage, $inpage) {
            endCurrPage = false;
            endNextPage = false;
            //resetPage( $outpage, $inpage );
            //isAnimating = false;
            $outpage.attr('class', $outpage.data('originalClassList'));
            $inpage.attr('class', $inpage.data('originalClassList') + ' pt-page-current');
        }

        //View切换
        this.changeView = function (newView) {
            var outClass = 'pt-page-flipOutTop';
            var inClass = 'pt-page-flipInBottom pt-page-delay500';

            var $currPage = $(".pt-page-current").eq(0);
            var $nextPage = $(newView);

            //清除原来添加的动画，层级等样式(正常动画结束时会自动清除，这样做防止用户在动画结束前就点击切换其他的)
            $(".pt-page").each(function () {
                $(this).attr('class', $(this).data('originalClassList'));
            });
            $currPage.addClass("pt-page-current");
            $nextPage.addClass("pt-page-current");


            //如果就是当页则不切换
            if ($currPage.attr("id") == $nextPage.attr("id")) {
                return;
            }

            //新页面入场
            $currPage.addClass(outClass).on(animEndEventName, function () {
                $currPage.off(animEndEventName);
                endCurrPage = true;
                if (endNextPage) {
                    self.onEndAnimation($currPage, $nextPage);
                }
            });

            //旧页面出场
            $nextPage.addClass(inClass).on(animEndEventName, function () {
                $nextPage.off(animEndEventName);
                endNextPage = true;
                if (endCurrPage) {
                    self.onEndAnimation($currPage, $nextPage);
                }
            });
        }

        this.loadCache = function() {
            if (self.restore) {
                var elementArr = self.kit.getCache(self.step2Key, 'elements');
                if (elementArr) {
                    $.each(elementArr, function(i, v) {
                        if (v.major) {
                            self.$major.attr('code', v.parentCode);
                            self.$major.val(v.context);
                            if (v.fillValue) {
                                self.$majorFill.val(v.fillValue);
                                self.$majorFill.css('display', 'block');
                            }
                            self.kit.setCache(self.step2Key, 'parentCategory1', v.pid);
                        } else {
                            self.$minor.attr('code', v.parentCode);
                            self.$minor.val(v.context);
                            if (v.fillValue) {
                                self.$minorFill.val(v.fillValue);
                                self.$minorFill.css('display', 'block');
                            }
                            self.kit.setCache(self.step2Key, 'parentCategory-1', v.pid);
                        }
                    });
                }
            } else {
                self.kit.setCache(self.step2Key, 'parentCategory1', '');
                self.kit.setCache(self.step2Key, 'parentCategory-1', '');
            }
        }

        /**
         * { 第二步提交 }
         *
         * @method     submitStep2
         */
        this.submitStep2 = function(e) {
            var selectedLi = $("ul#previewContainer li a.liSelected");
            if (selectedLi.length < 1) {
                Kit.alert2(self.i18n('pleaseSelectPreviewImage'));
                return;
            }
            self.kit.setCache(self.step2Key, 'imageUrl', selectedLi.data('image'));
            self.$root.trigger('enterStep3');
        }

        this.openChooseDialog = function(e) {
            var who = $(e.currentTarget).data('who');

            new ChooseDialogView().init(who, function(pid, code, prop, context) {
                var input = $(e.currentTarget).parent().prev();
                input.val(context);
                input.attr('pid', pid);
                input.attr('code', code);
                input.attr('prop', prop);
                if (prop == 2) {
                    $(e.currentTarget).parent().next().css('display', 'block');
                } else {
                    $(e.currentTarget).parent().next().css('display', 'none');
                }

            });
        }

        /**
         * 进入高级编辑页面
         */
        this.openHighEditView = function(e) {
            var who = $(e.currentTarget).data('who');
            self.changeView('#view2');
            var selectedLi = $("ul#previewContainer li a.liSelected");
            if (selectedLi.length < 1) {
                Kit.alert2(self.i18n('pleaseSelectPreviewImage'));
                return;
            }
            self.kit.setCache(self.step2Key, 'imageUrl', selectedLi.data('image'));

            new HighEditView().init(who, self.$major.attr('code'), self.$minor.attr('code'), function(pid, code, prop, context) {
                console.log('highedit back')
                /*var input = $(e.currentTarget).parent().prev();
                input.val(context);
                input.attr('pid', pid);
                input.attr('code', code);
                input.attr('prop', prop);
                if (prop == 2) {
                    $(e.currentTarget).parent().next().css('display', 'block');
                } else {
                    $(e.currentTarget).parent().next().css('display', 'none');
                }*/

            });
        }

        this.closeHighEditView = function(e) {
            self.changeView('#view1');
        }

        /**
         * { 主要元素、次要元素切换 }
         *
         * @method     swapElement
         */
        this.swapElement = function(e) {
            var swap = $(e.currentTarget).data('swap') * -1;

            self.$major.attr('type-a', swap);
            self.$minor.attr('type-a', swap * -1);

            var top = swap > 0 ? 0 : 110 * swap;
            self.$major.parent().animate({
                top: top * -1
            })
            self.$minor.parent().animate({
                top: top
            })
            $(e.currentTarget).data('swap', swap);

        }

        /**
         * { 生成创意预览 }
         *
         * @method     generate
         */
        this.generate = function(e) {
            if (Kit.isBlank(self.$major.val()) || Kit.isBlank(self.$minor.val())) {
                Kit.alert2(self.i18n('pleaseSelectCreativeElements'));
                return;
            }
            if (self.$majorFill.css('display') == 'block' && Kit.isBlank(self.$majorFill.val())) {
                Kit.alert2(self.i18n('pleaseEnterAFillValue'));
                return;
            }
            if (self.$minorFill.css('display') == 'block' && Kit.isBlank(self.$minorFill.val())) {
                Kit.alert2(self.i18n('pleaseEnterAFillValue'));
                return;
            }

            //每次点生成 - 清空右侧预览区
            self.$root.find('#previewContainer').empty();
            var elements = [{
                context: self.$major.val(),
                pid: self.$major.attr('pid'),
                parentCode: self.$major.attr('code'),
                major: (self.$major.attr('type-a') > 0),
                fillValue: self.$majorFill.val()
            }, {
                context: self.$minor.val(),
                pid: self.$minor.attr('pid'),
                parentCode: self.$minor.attr('code'),
                major: (self.$minor.attr('type-a') > 0),
                fillValue: self.$minorFill.val()
            }];
            self.kit.setCache(self.step2Key, 'elements', elements);
            var options = self.kit.getCache('createMaterialStep1', 'options');
            var generateParams = {
                wefeedid: self.kit.getCache(self.step1Key, 'feedId'),
                more: false,
                options: options,
                elements: elements
            }
            ecCreativeTemplateModel.buildCreative(generateParams, function(res) {
                //生成创意后 回调 发轮询请求 预览数据
                console.log(res);
                if (res && res.length > 0) {
                    $.each(res, function(i, obj) {
                        self.$root.find('#previewContainer').append('<li class="thumbnail-loading"><div class="col-md-4"><a class="thumbnail" data-image="./imgs/imgloading.gif"><img style="padding-top: 45%;" src="./imgs/imgloading.gif"> </a></div></li>');
                        self.$root.find('#previewContainer .thumbnail').height(self.$root.find('#previewContainer .thumbnail').width());
                    });
                    self.updatePreviewDiv(res);
                }
            });


        }

        /**
         * { 定时刷新预览图片 }
         *
         * @method     updatePreviewDiv
         */
        this.updatePreviewDiv = function(jobIds) {
            var _this = this;
            var len = jobIds.length;

            $.each(jobIds, function(a, b) {
                var jobParams = {
                    jobId: b,
                    _disabledShowloading: true
                }
                ecCreativeTemplateModel.buildCreativeResult(jobParams, function(res) {
                    console.log(res)
                    if (res && res.status == 2) {
                        var tplId = res.ecTemplate.id;
                        //预览图未生成完，继续渲染
                        $.each(res.feedList, function(i, v) {
                            var t = '<li><div class="col-md-4"><a class="thumbnail" data-template-id="' + tplId + '" data-image="' + v.image_link + '"><img src="' + v.image_link + '"> </a></div></li>';
                            $(t).appendTo(self.$root.find('#previewContainer'));
                            return;
                        });
                        self.$root.find('#previewContainer .thumbnail-loading').remove();
                        console.log('done--' + b);
                        jobIds.splice($.inArray(b, jobIds), 1);
                        if (len-- == 0) {
                            window.clearTimeout(_this.stoupdataState);
                        }
                        self.bindLiSelected();
                    }
                });
            });

            //定时刷新数据
            _this.stoupdataState = window.setTimeout(function() {
                _this.updatePreviewDiv(jobIds);
            }, 5000);
        }

        /**
         * 选择图增加互动
         */
        this.bindLiSelected = function() {
            $("ul#previewContainer li a").unbind("click").click(function(e) {
                $("ul#previewContainer li a").removeClass('liSelected');
                self.$root.find('.high-edit').removeClass('hidden');
                $(this).addClass("liSelected");
                var ecTplId = $(this).attr('data-template-id');
                self.kit.setCache(self.step2Key, 'ecTemplateId', ecTplId);
            });
        }

        this.i18n = function(key) {
            return I18N.getText('createMaterial', key)
        }
    }
    return me;
});